package com.lewin.ringroad.net;

import com.lewin.net.NetServer;
import com.lewin.net.ServerProperties;
import com.lewin.net.codec.HeadAndTailDelimiterBasedFrameDecoder;
import com.lewin.ringroad.net.handler.RaysunHandler;
import com.lewin.ringroad.net.message.RaysunMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 雷森雷达协议服务器
 *
 * @author Jun
 * @since 1.0.0
 */
@Component
public class RaySunRadarServerInitializer {

    private static final ByteBuf DELIMITER = Unpooled.wrappedBuffer(new byte[]{0x7e});

    private final RaysunHandler raysunHandler;

    public RaySunRadarServerInitializer(RaysunHandler raysunHandler) {
        this.raysunHandler = raysunHandler;
    }


    @PostConstruct
    private void init() throws InterruptedException {
        var p = new ServerProperties();
        p.setPort(1989);
        new NetServer(new ChannelInitializer<>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                var p = ch.pipeline();
                p.addLast(new IdleStateHandler(0, 0, 600));
                p.addLast(new HeadAndTailDelimiterBasedFrameDecoder(DELIMITER, DELIMITER, 1024 * 10));
                p.addLast(new MessageToMessageDecoder<ByteBuf>() {
                    @Override
                    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) {
                        out.add(RaysunMessage.parseFrom(msg));
                    }
                });
                p.addLast(raysunHandler);
            }
        }, p).start();
    }
}
